home *** CD-ROM | disk | FTP | other *** search
/ Freelog 125 / Freelog_MarsAvril2015_No125.iso / Musique / Quod Libet / quodlibet-3.3.0-portable.exe / quodlibet-3.3.0-portable / data / bin / optparse.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2014-12-31  |  51KB  |  1,464 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.7)
  3.  
  4. '''A powerful, extensible, and easy-to-use option parser.
  5.  
  6. By Greg Ward <gward@python.net>
  7.  
  8. Originally distributed as Optik.
  9.  
  10. For support, use the optik-users@lists.sourceforge.net mailing list
  11. (http://lists.sourceforge.net/lists/listinfo/optik-users).
  12.  
  13. Simple usage example:
  14.  
  15.    from optparse import OptionParser
  16.  
  17.    parser = OptionParser()
  18.    parser.add_option("-f", "--file", dest="filename",
  19.                      help="write report to FILE", metavar="FILE")
  20.    parser.add_option("-q", "--quiet",
  21.                      action="store_false", dest="verbose", default=True,
  22.                      help="don\'t print status messages to stdout")
  23.  
  24.    (options, args) = parser.parse_args()
  25. '''
  26. __version__ = '1.5.3'
  27. __all__ = [
  28.     'Option',
  29.     'make_option',
  30.     'SUPPRESS_HELP',
  31.     'SUPPRESS_USAGE',
  32.     'Values',
  33.     'OptionContainer',
  34.     'OptionGroup',
  35.     'OptionParser',
  36.     'HelpFormatter',
  37.     'IndentedHelpFormatter',
  38.     'TitledHelpFormatter',
  39.     'OptParseError',
  40.     'OptionError',
  41.     'OptionConflictError',
  42.     'OptionValueError',
  43.     'BadOptionError']
  44. __copyright__ = '\nCopyright (c) 2001-2006 Gregory P. Ward.  All rights reserved.\nCopyright (c) 2002-2006 Python Software Foundation.  All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n  * Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n\n  * Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n\n  * Neither the name of the author nor the names of its\n    contributors may be used to endorse or promote products derived from\n    this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS\nIS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\nTO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\nPARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n'
  45. import sys
  46. import os
  47. import types
  48. import textwrap
  49.  
  50. def _repr(self):
  51.     return '<%s at 0x%x: %s>' % (self.__class__.__name__, id(self), self)
  52.  
  53.  
  54. try:
  55.     from gettext import gettext
  56. except ImportError:
  57.     
  58.     def gettext(message):
  59.         return message
  60.  
  61.  
  62. _ = gettext
  63.  
  64. class OptParseError(Exception):
  65.     
  66.     def __init__(self, msg):
  67.         self.msg = msg
  68.  
  69.     
  70.     def __str__(self):
  71.         return self.msg
  72.  
  73.  
  74.  
  75. class OptionError(OptParseError):
  76.     '''
  77.     Raised if an Option instance is created with invalid or
  78.     inconsistent arguments.
  79.     '''
  80.     
  81.     def __init__(self, msg, option):
  82.         self.msg = msg
  83.         self.option_id = str(option)
  84.  
  85.     
  86.     def __str__(self):
  87.         if self.option_id:
  88.             return 'option %s: %s' % (self.option_id, self.msg)
  89.         return None.msg
  90.  
  91.  
  92.  
  93. class OptionConflictError(OptionError):
  94.     '''
  95.     Raised if conflicting options are added to an OptionParser.
  96.     '''
  97.     pass
  98.  
  99.  
  100. class OptionValueError(OptParseError):
  101.     '''
  102.     Raised if an invalid option value is encountered on the command
  103.     line.
  104.     '''
  105.     pass
  106.  
  107.  
  108. class BadOptionError(OptParseError):
  109.     '''
  110.     Raised if an invalid option is seen on the command line.
  111.     '''
  112.     
  113.     def __init__(self, opt_str):
  114.         self.opt_str = opt_str
  115.  
  116.     
  117.     def __str__(self):
  118.         return _('no such option: %s') % self.opt_str
  119.  
  120.  
  121.  
  122. class AmbiguousOptionError(BadOptionError):
  123.     '''
  124.     Raised if an ambiguous option is seen on the command line.
  125.     '''
  126.     
  127.     def __init__(self, opt_str, possibilities):
  128.         BadOptionError.__init__(self, opt_str)
  129.         self.possibilities = possibilities
  130.  
  131.     
  132.     def __str__(self):
  133.         return _('ambiguous option: %s (%s?)') % (self.opt_str, ', '.join(self.possibilities))
  134.  
  135.  
  136.  
  137. class HelpFormatter:
  138.     '''
  139.     Abstract base class for formatting option help.  OptionParser
  140.     instances should use one of the HelpFormatter subclasses for
  141.     formatting help; by default IndentedHelpFormatter is used.
  142.  
  143.     Instance attributes:
  144.       parser : OptionParser
  145.         the controlling OptionParser instance
  146.       indent_increment : int
  147.         the number of columns to indent per nesting level
  148.       max_help_position : int
  149.         the maximum starting column for option help text
  150.       help_position : int
  151.         the calculated starting column for option help text;
  152.         initially the same as the maximum
  153.       width : int
  154.         total number of columns for output (pass None to constructor for
  155.         this value to be taken from the $COLUMNS environment variable)
  156.       level : int
  157.         current indentation level
  158.       current_indent : int
  159.         current indentation level (in columns)
  160.       help_width : int
  161.         number of columns available for option help text (calculated)
  162.       default_tag : str
  163.         text to replace with each option\'s default value, "%default"
  164.         by default.  Set to false value to disable default value expansion.
  165.       option_strings : { Option : str }
  166.         maps Option instances to the snippet of help text explaining
  167.         the syntax of that option, e.g. "-h, --help" or
  168.         "-fFILE, --file=FILE"
  169.       _short_opt_fmt : str
  170.         format string controlling how short options with values are
  171.         printed in help text.  Must be either "%s%s" ("-fFILE") or
  172.         "%s %s" ("-f FILE"), because those are the two syntaxes that
  173.         Optik supports.
  174.       _long_opt_fmt : str
  175.         similar but for long options; must be either "%s %s" ("--file FILE")
  176.         or "%s=%s" ("--file=FILE").
  177.     '''
  178.     NO_DEFAULT_VALUE = 'none'
  179.     
  180.     def __init__(self, indent_increment, max_help_position, width, short_first):
  181.         self.parser = None
  182.         self.indent_increment = indent_increment
  183.         self.help_position = self.max_help_position = max_help_position
  184.         if width is None:
  185.             
  186.             try:
  187.                 width = int(os.environ['COLUMNS'])
  188.             except (KeyError, ValueError):
  189.                 width = 80
  190.  
  191.             width -= 2
  192.         self.width = width
  193.         self.current_indent = 0
  194.         self.level = 0
  195.         self.help_width = None
  196.         self.short_first = short_first
  197.         self.default_tag = '%default'
  198.         self.option_strings = { }
  199.         self._short_opt_fmt = '%s %s'
  200.         self._long_opt_fmt = '%s=%s'
  201.  
  202.     
  203.     def set_parser(self, parser):
  204.         self.parser = parser
  205.  
  206.     
  207.     def set_short_opt_delimiter(self, delim):
  208.         if delim not in ('', ' '):
  209.             raise ValueError('invalid metavar delimiter for short options: %r' % delim)
  210.         self._short_opt_fmt = '%s' + delim + '%s'
  211.  
  212.     
  213.     def set_long_opt_delimiter(self, delim):
  214.         if delim not in ('=', ' '):
  215.             raise ValueError('invalid metavar delimiter for long options: %r' % delim)
  216.         self._long_opt_fmt = '%s' + delim + '%s'
  217.  
  218.     
  219.     def indent(self):
  220.         self.current_indent += self.indent_increment
  221.         self.level += 1
  222.  
  223.     
  224.     def dedent(self):
  225.         self.current_indent -= self.indent_increment
  226.         if not self.current_indent >= 0:
  227.             raise AssertionError('Indent decreased below 0.')
  228.         self.level -= 1
  229.  
  230.     
  231.     def format_usage(self, usage):
  232.         raise NotImplementedError, 'subclasses must implement'
  233.  
  234.     
  235.     def format_heading(self, heading):
  236.         raise NotImplementedError, 'subclasses must implement'
  237.  
  238.     
  239.     def _format_text(self, text):
  240.         '''
  241.         Format a paragraph of free-form text for inclusion in the
  242.         help output at the current indentation level.
  243.         '''
  244.         text_width = self.width - self.current_indent
  245.         indent = ' ' * self.current_indent
  246.         return textwrap.fill(text, text_width, initial_indent = indent, subsequent_indent = indent)
  247.  
  248.     
  249.     def format_description(self, description):
  250.         if description:
  251.             return self._format_text(description) + '\n'
  252.         return None
  253.  
  254.     
  255.     def format_epilog(self, epilog):
  256.         if epilog:
  257.             return '\n' + self._format_text(epilog) + '\n'
  258.         return None
  259.  
  260.     
  261.     def expand_default(self, option):
  262.         if self.parser is None or not (self.default_tag):
  263.             return option.help
  264.         default_value = None.parser.defaults.get(option.dest)
  265.         if default_value is NO_DEFAULT or default_value is None:
  266.             default_value = self.NO_DEFAULT_VALUE
  267.         return option.help.replace(self.default_tag, str(default_value))
  268.  
  269.     
  270.     def format_option(self, option):
  271.         result = []
  272.         opts = self.option_strings[option]
  273.         opt_width = self.help_position - self.current_indent - 2
  274.         if len(opts) > opt_width:
  275.             opts = '%*s%s\n' % (self.current_indent, '', opts)
  276.             indent_first = self.help_position
  277.         else:
  278.             opts = '%*s%-*s  ' % (self.current_indent, '', opt_width, opts)
  279.             indent_first = 0
  280.         result.append(opts)
  281.         if option.help:
  282.             help_text = self.expand_default(option)
  283.             help_lines = textwrap.wrap(help_text, self.help_width)
  284.             result.append('%*s%s\n' % (indent_first, '', help_lines[0]))
  285.             result.extend([ '%*s%s\n' % (self.help_position, '', line) for line in help_lines[1:] ])
  286.         elif opts[-1] != '\n':
  287.             result.append('\n')
  288.         return ''.join(result)
  289.  
  290.     
  291.     def store_option_strings(self, parser):
  292.         self.indent()
  293.         max_len = 0
  294.         for opt in parser.option_list:
  295.             strings = self.format_option_strings(opt)
  296.             self.option_strings[opt] = strings
  297.             max_len = max(max_len, len(strings) + self.current_indent)
  298.         
  299.         self.indent()
  300.         for group in parser.option_groups:
  301.             for opt in group.option_list:
  302.                 strings = self.format_option_strings(opt)
  303.                 self.option_strings[opt] = strings
  304.                 max_len = max(max_len, len(strings) + self.current_indent)
  305.             
  306.         
  307.         self.dedent()
  308.         self.dedent()
  309.         self.help_position = min(max_len + 2, self.max_help_position)
  310.         self.help_width = self.width - self.help_position
  311.  
  312.     
  313.     def format_option_strings(self, option):
  314.         '''Return a comma-separated list of option strings & metavariables.'''
  315.         if option.takes_value():
  316.             if not option.metavar:
  317.                 pass
  318.             metavar = option.dest.upper()
  319.             short_opts = [ self._short_opt_fmt % (sopt, metavar) for sopt in option._short_opts ]
  320.             long_opts = [ self._long_opt_fmt % (lopt, metavar) for lopt in option._long_opts ]
  321.         else:
  322.             short_opts = option._short_opts
  323.             long_opts = option._long_opts
  324.         if self.short_first:
  325.             opts = short_opts + long_opts
  326.         else:
  327.             opts = long_opts + short_opts
  328.         return ', '.join(opts)
  329.  
  330.  
  331.  
  332. class IndentedHelpFormatter(HelpFormatter):
  333.     '''Format help with indented section bodies.
  334.     '''
  335.     
  336.     def __init__(self, indent_increment = 2, max_help_position = 24, width = None, short_first = 1):
  337.         HelpFormatter.__init__(self, indent_increment, max_help_position, width, short_first)
  338.  
  339.     
  340.     def format_usage(self, usage):
  341.         return _('Usage: %s\n') % usage
  342.  
  343.     
  344.     def format_heading(self, heading):
  345.         return '%*s%s:\n' % (self.current_indent, '', heading)
  346.  
  347.  
  348.  
  349. class TitledHelpFormatter(HelpFormatter):
  350.     '''Format help with underlined section headers.
  351.     '''
  352.     
  353.     def __init__(self, indent_increment = 0, max_help_position = 24, width = None, short_first = 0):
  354.         HelpFormatter.__init__(self, indent_increment, max_help_position, width, short_first)
  355.  
  356.     
  357.     def format_usage(self, usage):
  358.         return '%s  %s\n' % (self.format_heading(_('Usage')), usage)
  359.  
  360.     
  361.     def format_heading(self, heading):
  362.         return '%s\n%s\n' % (heading, '=-'[self.level] * len(heading))
  363.  
  364.  
  365.  
  366. def _parse_num(val, type):
  367.     if val[:2].lower() == '0x':
  368.         radix = 16
  369.     elif val[:2].lower() == '0b':
  370.         radix = 2
  371.         if not val[2:]:
  372.             pass
  373.         val = '0'
  374.     elif val[:1] == '0':
  375.         radix = 8
  376.     else:
  377.         radix = 10
  378.     return type(val, radix)
  379.  
  380.  
  381. def _parse_int(val):
  382.     return _parse_num(val, int)
  383.  
  384.  
  385. def _parse_long(val):
  386.     return _parse_num(val, long)
  387.  
  388. _builtin_cvt = {
  389.     'int': (_parse_int, _('integer')),
  390.     'long': (_parse_long, _('long integer')),
  391.     'float': (float, _('floating-point')),
  392.     'complex': (complex, _('complex')) }
  393.  
  394. def check_builtin(option, opt, value):
  395.     (cvt, what) = _builtin_cvt[option.type]
  396.     
  397.     try:
  398.         return cvt(value)
  399.     except ValueError:
  400.         raise OptionValueError(_('option %s: invalid %s value: %r') % (opt, what, value))
  401.  
  402.  
  403.  
  404. def check_choice(option, opt, value):
  405.     if value in option.choices:
  406.         return value
  407.     choices = None.join(map(repr, option.choices))
  408.     raise OptionValueError(_('option %s: invalid choice: %r (choose from %s)') % (opt, value, choices))
  409.  
  410. NO_DEFAULT = ('NO', 'DEFAULT')
  411.  
  412. class Option:
  413.     '''
  414.     Instance attributes:
  415.       _short_opts : [string]
  416.       _long_opts : [string]
  417.  
  418.       action : string
  419.       type : string
  420.       dest : string
  421.       default : any
  422.       nargs : int
  423.       const : any
  424.       choices : [string]
  425.       callback : function
  426.       callback_args : (any*)
  427.       callback_kwargs : { string : any }
  428.       help : string
  429.       metavar : string
  430.     '''
  431.     ATTRS = [
  432.         'action',
  433.         'type',
  434.         'dest',
  435.         'default',
  436.         'nargs',
  437.         'const',
  438.         'choices',
  439.         'callback',
  440.         'callback_args',
  441.         'callback_kwargs',
  442.         'help',
  443.         'metavar']
  444.     ACTIONS = ('store', 'store_const', 'store_true', 'store_false', 'append', 'append_const', 'count', 'callback', 'help', 'version')
  445.     STORE_ACTIONS = ('store', 'store_const', 'store_true', 'store_false', 'append', 'append_const', 'count')
  446.     TYPED_ACTIONS = ('store', 'append', 'callback')
  447.     ALWAYS_TYPED_ACTIONS = ('store', 'append')
  448.     CONST_ACTIONS = ('store_const', 'append_const')
  449.     TYPES = ('string', 'int', 'long', 'float', 'complex', 'choice')
  450.     TYPE_CHECKER = {
  451.         'int': check_builtin,
  452.         'long': check_builtin,
  453.         'float': check_builtin,
  454.         'complex': check_builtin,
  455.         'choice': check_choice }
  456.     CHECK_METHODS = None
  457.     
  458.     def __init__(self, *opts, **attrs):
  459.         self._short_opts = []
  460.         self._long_opts = []
  461.         opts = self._check_opt_strings(opts)
  462.         self._set_opt_strings(opts)
  463.         self._set_attrs(attrs)
  464.         for checker in self.CHECK_METHODS:
  465.             checker(self)
  466.         
  467.  
  468.     
  469.     def _check_opt_strings(self, opts):
  470.         opts = filter(None, opts)
  471.         if not opts:
  472.             raise TypeError('at least one option string must be supplied')
  473.         return opts
  474.  
  475.     
  476.     def _set_opt_strings(self, opts):
  477.         for opt in opts:
  478.             if len(opt) < 2:
  479.                 raise OptionError('invalid option string %r: must be at least two characters long' % opt, self)
  480.             if len(opt) == 2:
  481.                 if not opt[0] == '-' and opt[1] != '-':
  482.                     raise OptionError('invalid short option string %r: must be of the form -x, (x any non-dash char)' % opt, self)
  483.                 self._short_opts.append(opt)
  484.                 continue
  485.             if not opt[0:2] == '--' and opt[2] != '-':
  486.                 raise OptionError('invalid long option string %r: must start with --, followed by non-dash' % opt, self)
  487.             self._long_opts.append(opt)
  488.         
  489.  
  490.     
  491.     def _set_attrs(self, attrs):
  492.         for attr in self.ATTRS:
  493.             if attr in attrs:
  494.                 setattr(self, attr, attrs[attr])
  495.                 del attrs[attr]
  496.                 continue
  497.             if attr == 'default':
  498.                 setattr(self, attr, NO_DEFAULT)
  499.                 continue
  500.             setattr(self, attr, None)
  501.         
  502.         if attrs:
  503.             attrs = attrs.keys()
  504.             attrs.sort()
  505.             raise OptionError('invalid keyword arguments: %s' % ', '.join(attrs), self)
  506.  
  507.     
  508.     def _check_action(self):
  509.         if self.action is None:
  510.             self.action = 'store'
  511.         elif self.action not in self.ACTIONS:
  512.             raise OptionError('invalid action: %r' % self.action, self)
  513.  
  514.     
  515.     def _check_type(self):
  516.         if self.type is None or self.action in self.ALWAYS_TYPED_ACTIONS:
  517.             if self.choices is not None:
  518.                 self.type = 'choice'
  519.             else:
  520.                 self.type = 'string'
  521.         
  522.         import __builtin__ as __builtin__
  523.         if (type(self.type) is types.TypeType or hasattr(self.type, '__name__')) and getattr(__builtin__, self.type.__name__, None) is self.type:
  524.             self.type = self.type.__name__
  525.         if self.type == 'str':
  526.             self.type = 'string'
  527.         if self.type not in self.TYPES:
  528.             raise OptionError('invalid option type: %r' % self.type, self)
  529.         if self.action not in self.TYPED_ACTIONS:
  530.             raise OptionError('must not supply a type for action %r' % self.action, self)
  531.  
  532.     
  533.     def _check_choice(self):
  534.         if self.type == 'choice':
  535.             if self.choices is None:
  536.                 raise OptionError("must supply a list of choices for type 'choice'", self)
  537.             if type(self.choices) not in (types.TupleType, types.ListType):
  538.                 raise OptionError("choices must be a list of strings ('%s' supplied)" % str(type(self.choices)).split("'")[1], self)
  539.         elif self.choices is not None:
  540.             raise OptionError('must not supply choices for type %r' % self.type, self)
  541.  
  542.     
  543.     def _check_dest(self):
  544.         if not self.action in self.STORE_ACTIONS:
  545.             pass
  546.         takes_value = self.type is not None
  547.         if self.dest is None and takes_value:
  548.             if self._long_opts:
  549.                 self.dest = self._long_opts[0][2:].replace('-', '_')
  550.             else:
  551.                 self.dest = self._short_opts[0][1]
  552.  
  553.     
  554.     def _check_const(self):
  555.         if self.action not in self.CONST_ACTIONS and self.const is not None:
  556.             raise OptionError("'const' must not be supplied for action %r" % self.action, self)
  557.  
  558.     
  559.     def _check_nargs(self):
  560.         if self.action in self.TYPED_ACTIONS or self.nargs is None:
  561.             self.nargs = 1
  562.         
  563.         if self.nargs is not None:
  564.             raise OptionError("'nargs' must not be supplied for action %r" % self.action, self)
  565.  
  566.     
  567.     def _check_callback(self):
  568.         if self.action == 'callback':
  569.             if not hasattr(self.callback, '__call__'):
  570.                 raise OptionError('callback not callable: %r' % self.callback, self)
  571.             if self.callback_args is not None and type(self.callback_args) is not types.TupleType:
  572.                 raise OptionError('callback_args, if supplied, must be a tuple: not %r' % self.callback_args, self)
  573.             if self.callback_kwargs is not None and type(self.callback_kwargs) is not types.DictType:
  574.                 raise OptionError('callback_kwargs, if supplied, must be a dict: not %r' % self.callback_kwargs, self)
  575.         elif self.callback is not None:
  576.             raise OptionError('callback supplied (%r) for non-callback option' % self.callback, self)
  577.         if self.callback_args is not None:
  578.             raise OptionError('callback_args supplied for non-callback option', self)
  579.         if self.callback_kwargs is not None:
  580.             raise OptionError('callback_kwargs supplied for non-callback option', self)
  581.  
  582.     CHECK_METHODS = [
  583.         _check_action,
  584.         _check_type,
  585.         _check_choice,
  586.         _check_dest,
  587.         _check_const,
  588.         _check_nargs,
  589.         _check_callback]
  590.     
  591.     def __str__(self):
  592.         return '/'.join(self._short_opts + self._long_opts)
  593.  
  594.     __repr__ = _repr
  595.     
  596.     def takes_value(self):
  597.         return self.type is not None
  598.  
  599.     
  600.     def get_opt_string(self):
  601.         if self._long_opts:
  602.             return self._long_opts[0]
  603.         return None._short_opts[0]
  604.  
  605.     
  606.     def check_value(self, opt, value):
  607.         checker = self.TYPE_CHECKER.get(self.type)
  608.         if checker is None:
  609.             return value
  610.         return None(self, opt, value)
  611.  
  612.     
  613.     def convert_value(self, opt, value):
  614.         if value is not None:
  615.             if self.nargs == 1:
  616.                 return self.check_value(opt, value)
  617.             return None([ self.check_value(opt, v) for v in value ])
  618.  
  619.     
  620.     def process(self, opt, value, values, parser):
  621.         value = self.convert_value(opt, value)
  622.         return self.take_action(self.action, self.dest, opt, value, values, parser)
  623.  
  624.     
  625.     def take_action(self, action, dest, opt, value, values, parser):
  626.         if action == 'store':
  627.             setattr(values, dest, value)
  628.         elif action == 'store_const':
  629.             setattr(values, dest, self.const)
  630.         elif action == 'store_true':
  631.             setattr(values, dest, True)
  632.         elif action == 'store_false':
  633.             setattr(values, dest, False)
  634.         elif action == 'append':
  635.             values.ensure_value(dest, []).append(value)
  636.         elif action == 'append_const':
  637.             values.ensure_value(dest, []).append(self.const)
  638.         elif action == 'count':
  639.             setattr(values, dest, values.ensure_value(dest, 0) + 1)
  640.         elif action == 'callback':
  641.             if not self.callback_args:
  642.                 pass
  643.             args = ()
  644.             if not self.callback_kwargs:
  645.                 pass
  646.             kwargs = { }
  647.             self.callback(self, opt, value, parser, *args, **kwargs)
  648.         elif action == 'help':
  649.             parser.print_help()
  650.             parser.exit()
  651.         elif action == 'version':
  652.             parser.print_version()
  653.             parser.exit()
  654.         else:
  655.             raise ValueError('unknown action %r' % self.action)
  656.  
  657.  
  658. SUPPRESS_HELP = 'SUPPRESS' + 'HELP'
  659. SUPPRESS_USAGE = 'SUPPRESS' + 'USAGE'
  660.  
  661. try:
  662.     basestring
  663. except NameError:
  664.     
  665.     def isbasestring(x):
  666.         return isinstance(x, (types.StringType, types.UnicodeType))
  667.  
  668.  
  669.  
  670. def isbasestring(x):
  671.     return isinstance(x, basestring)
  672.  
  673.  
  674. class Values:
  675.     
  676.     def __init__(self, defaults = None):
  677.         if defaults:
  678.             for attr, val in defaults.items():
  679.                 setattr(self, attr, val)
  680.             
  681.  
  682.     
  683.     def __str__(self):
  684.         return str(self.__dict__)
  685.  
  686.     __repr__ = _repr
  687.     
  688.     def __cmp__(self, other):
  689.         if isinstance(other, Values):
  690.             return cmp(self.__dict__, other.__dict__)
  691.         if None(other, types.DictType):
  692.             return cmp(self.__dict__, other)
  693.         return None
  694.  
  695.     
  696.     def _update_careful(self, dict):
  697.         '''
  698.         Update the option values from an arbitrary dictionary, but only
  699.         use keys from dict that already have a corresponding attribute
  700.         in self.  Any keys in dict without a corresponding attribute
  701.         are silently ignored.
  702.         '''
  703.         for attr in dir(self):
  704.             if attr in dict:
  705.                 dval = dict[attr]
  706.                 if dval is not None:
  707.                     setattr(self, attr, dval)
  708.                 
  709.  
  710.     
  711.     def _update_loose(self, dict):
  712.         '''
  713.         Update the option values from an arbitrary dictionary,
  714.         using all keys from the dictionary regardless of whether
  715.         they have a corresponding attribute in self or not.
  716.         '''
  717.         self.__dict__.update(dict)
  718.  
  719.     
  720.     def _update(self, dict, mode):
  721.         if mode == 'careful':
  722.             self._update_careful(dict)
  723.         elif mode == 'loose':
  724.             self._update_loose(dict)
  725.         else:
  726.             raise ValueError, 'invalid update mode: %r' % mode
  727.  
  728.     
  729.     def read_module(self, modname, mode = 'careful'):
  730.         __import__(modname)
  731.         mod = sys.modules[modname]
  732.         self._update(vars(mod), mode)
  733.  
  734.     
  735.     def read_file(self, filename, mode = 'careful'):
  736.         vars = { }
  737.         execfile(filename, vars)
  738.         self._update(vars, mode)
  739.  
  740.     
  741.     def ensure_value(self, attr, value):
  742.         if not hasattr(self, attr) or getattr(self, attr) is None:
  743.             setattr(self, attr, value)
  744.         return getattr(self, attr)
  745.  
  746.  
  747.  
  748. class OptionContainer:
  749.     '''
  750.     Abstract base class.
  751.  
  752.     Class attributes:
  753.       standard_option_list : [Option]
  754.         list of standard options that will be accepted by all instances
  755.         of this parser class (intended to be overridden by subclasses).
  756.  
  757.     Instance attributes:
  758.       option_list : [Option]
  759.         the list of Option objects contained by this OptionContainer
  760.       _short_opt : { string : Option }
  761.         dictionary mapping short option strings, eg. "-f" or "-X",
  762.         to the Option instances that implement them.  If an Option
  763.         has multiple short option strings, it will appears in this
  764.         dictionary multiple times. [1]
  765.       _long_opt : { string : Option }
  766.         dictionary mapping long option strings, eg. "--file" or
  767.         "--exclude", to the Option instances that implement them.
  768.         Again, a given Option can occur multiple times in this
  769.         dictionary. [1]
  770.       defaults : { string : any }
  771.         dictionary mapping option destination names to default
  772.         values for each destination [1]
  773.  
  774.     [1] These mappings are common to (shared by) all components of the
  775.         controlling OptionParser, where they are initially created.
  776.  
  777.     '''
  778.     
  779.     def __init__(self, option_class, conflict_handler, description):
  780.         self._create_option_list()
  781.         self.option_class = option_class
  782.         self.set_conflict_handler(conflict_handler)
  783.         self.set_description(description)
  784.  
  785.     
  786.     def _create_option_mappings(self):
  787.         self._short_opt = { }
  788.         self._long_opt = { }
  789.         self.defaults = { }
  790.  
  791.     
  792.     def _share_option_mappings(self, parser):
  793.         self._short_opt = parser._short_opt
  794.         self._long_opt = parser._long_opt
  795.         self.defaults = parser.defaults
  796.  
  797.     
  798.     def set_conflict_handler(self, handler):
  799.         if handler not in ('error', 'resolve'):
  800.             raise ValueError, 'invalid conflict_resolution value %r' % handler
  801.         self.conflict_handler = handler
  802.  
  803.     
  804.     def set_description(self, description):
  805.         self.description = description
  806.  
  807.     
  808.     def get_description(self):
  809.         return self.description
  810.  
  811.     
  812.     def destroy(self):
  813.         '''see OptionParser.destroy().'''
  814.         del self._short_opt
  815.         del self._long_opt
  816.         del self.defaults
  817.  
  818.     
  819.     def _check_conflict(self, option):
  820.         conflict_opts = []
  821.         for opt in option._short_opts:
  822.             if opt in self._short_opt:
  823.                 conflict_opts.append((opt, self._short_opt[opt]))
  824.                 continue
  825.         for opt in option._long_opts:
  826.             if opt in self._long_opt:
  827.                 conflict_opts.append((opt, self._long_opt[opt]))
  828.                 continue
  829.         if conflict_opts:
  830.             handler = self.conflict_handler
  831.  
  832.     
  833.     def add_option(self, *args, **kwargs):
  834.         '''add_option(Option)
  835.            add_option(opt_str, ..., kwarg=val, ...)
  836.         '''
  837.         if type(args[0]) in types.StringTypes:
  838.             option = self.option_class(*args, **kwargs)
  839.         elif len(args) == 1 and not kwargs:
  840.             option = args[0]
  841.             if not isinstance(option, Option):
  842.                 raise TypeError, 'not an Option instance: %r' % option
  843.         else:
  844.             raise TypeError, 'invalid arguments'
  845.         None._check_conflict(option)
  846.         self.option_list.append(option)
  847.         option.container = self
  848.         for opt in option._short_opts:
  849.             self._short_opt[opt] = option
  850.         
  851.         for opt in option._long_opts:
  852.             self._long_opt[opt] = option
  853.         
  854.         if option.dest is not None:
  855.             if option.default is not NO_DEFAULT:
  856.                 self.defaults[option.dest] = option.default
  857.             elif option.dest not in self.defaults:
  858.                 self.defaults[option.dest] = None
  859.             
  860.         return option
  861.  
  862.     
  863.     def add_options(self, option_list):
  864.         for option in option_list:
  865.             self.add_option(option)
  866.         
  867.  
  868.     
  869.     def get_option(self, opt_str):
  870.         if not self._short_opt.get(opt_str):
  871.             pass
  872.         return self._long_opt.get(opt_str)
  873.  
  874.     
  875.     def has_option(self, opt_str):
  876.         if not opt_str in self._short_opt:
  877.             pass
  878.         return opt_str in self._long_opt
  879.  
  880.     
  881.     def remove_option(self, opt_str):
  882.         option = self._short_opt.get(opt_str)
  883.         if option is None:
  884.             option = self._long_opt.get(opt_str)
  885.         if option is None:
  886.             raise ValueError('no such option %r' % opt_str)
  887.         for opt in option._short_opts:
  888.             del self._short_opt[opt]
  889.         
  890.         for opt in option._long_opts:
  891.             del self._long_opt[opt]
  892.         
  893.         option.container.option_list.remove(option)
  894.  
  895.     
  896.     def format_option_help(self, formatter):
  897.         if not self.option_list:
  898.             return ''
  899.         result = None
  900.         for option in self.option_list:
  901.             if option.help is not SUPPRESS_HELP:
  902.                 result.append(formatter.format_option(option))
  903.                 continue
  904.         return ''.join(result)
  905.  
  906.     
  907.     def format_description(self, formatter):
  908.         return formatter.format_description(self.get_description())
  909.  
  910.     
  911.     def format_help(self, formatter):
  912.         result = []
  913.         if self.description:
  914.             result.append(self.format_description(formatter))
  915.         if self.option_list:
  916.             result.append(self.format_option_help(formatter))
  917.         return '\n'.join(result)
  918.  
  919.  
  920.  
  921. class OptionGroup(OptionContainer):
  922.     
  923.     def __init__(self, parser, title, description = None):
  924.         self.parser = parser
  925.         OptionContainer.__init__(self, parser.option_class, parser.conflict_handler, description)
  926.         self.title = title
  927.  
  928.     
  929.     def _create_option_list(self):
  930.         self.option_list = []
  931.         self._share_option_mappings(self.parser)
  932.  
  933.     
  934.     def set_title(self, title):
  935.         self.title = title
  936.  
  937.     
  938.     def destroy(self):
  939.         '''see OptionParser.destroy().'''
  940.         OptionContainer.destroy(self)
  941.         del self.option_list
  942.  
  943.     
  944.     def format_help(self, formatter):
  945.         result = formatter.format_heading(self.title)
  946.         formatter.indent()
  947.         result += OptionContainer.format_help(self, formatter)
  948.         formatter.dedent()
  949.         return result
  950.  
  951.  
  952.  
  953. class OptionParser(OptionContainer):
  954.     '''
  955.     Class attributes:
  956.       standard_option_list : [Option]
  957.         list of standard options that will be accepted by all instances
  958.         of this parser class (intended to be overridden by subclasses).
  959.  
  960.     Instance attributes:
  961.       usage : string
  962.         a usage string for your program.  Before it is displayed
  963.         to the user, "%prog" will be expanded to the name of
  964.         your program (self.prog or os.path.basename(sys.argv[0])).
  965.       prog : string
  966.         the name of the current program (to override
  967.         os.path.basename(sys.argv[0])).
  968.       description : string
  969.         A paragraph of text giving a brief overview of your program.
  970.         optparse reformats this paragraph to fit the current terminal
  971.         width and prints it when the user requests help (after usage,
  972.         but before the list of options).
  973.       epilog : string
  974.         paragraph of help text to print after option help
  975.  
  976.       option_groups : [OptionGroup]
  977.         list of option groups in this parser (option groups are
  978.         irrelevant for parsing the command-line, but very useful
  979.         for generating help)
  980.  
  981.       allow_interspersed_args : bool = true
  982.         if true, positional arguments may be interspersed with options.
  983.         Assuming -a and -b each take a single argument, the command-line
  984.           -ablah foo bar -bboo baz
  985.         will be interpreted the same as
  986.           -ablah -bboo -- foo bar baz
  987.         If this flag were false, that command line would be interpreted as
  988.           -ablah -- foo bar -bboo baz
  989.         -- ie. we stop processing options as soon as we see the first
  990.         non-option argument.  (This is the tradition followed by
  991.         Python\'s getopt module, Perl\'s Getopt::Std, and other argument-
  992.         parsing libraries, but it is generally annoying to users.)
  993.  
  994.       process_default_values : bool = true
  995.         if true, option default values are processed similarly to option
  996.         values from the command line: that is, they are passed to the
  997.         type-checking function for the option\'s type (as long as the
  998.         default value is a string).  (This really only matters if you
  999.         have defined custom types; see SF bug #955889.)  Set it to false
  1000.         to restore the behaviour of Optik 1.4.1 and earlier.
  1001.  
  1002.       rargs : [string]
  1003.         the argument list currently being parsed.  Only set when
  1004.         parse_args() is active, and continually trimmed down as
  1005.         we consume arguments.  Mainly there for the benefit of
  1006.         callback options.
  1007.       largs : [string]
  1008.         the list of leftover arguments that we have skipped while
  1009.         parsing options.  If allow_interspersed_args is false, this
  1010.         list is always empty.
  1011.       values : Values
  1012.         the set of option values currently being accumulated.  Only
  1013.         set when parse_args() is active.  Also mainly for callbacks.
  1014.  
  1015.     Because of the \'rargs\', \'largs\', and \'values\' attributes,
  1016.     OptionParser is not thread-safe.  If, for some perverse reason, you
  1017.     need to parse command-line arguments simultaneously in different
  1018.     threads, use different OptionParser instances.
  1019.  
  1020.     '''
  1021.     standard_option_list = []
  1022.     
  1023.     def __init__(self, usage = None, option_list = None, option_class = Option, version = None, conflict_handler = 'error', description = None, formatter = None, add_help_option = True, prog = None, epilog = None):
  1024.         OptionContainer.__init__(self, option_class, conflict_handler, description)
  1025.         self.set_usage(usage)
  1026.         self.prog = prog
  1027.         self.version = version
  1028.         self.allow_interspersed_args = True
  1029.         self.process_default_values = True
  1030.         if formatter is None:
  1031.             formatter = IndentedHelpFormatter()
  1032.         self.formatter = formatter
  1033.         self.formatter.set_parser(self)
  1034.         self.epilog = epilog
  1035.         self._populate_option_list(option_list, add_help = add_help_option)
  1036.         self._init_parsing_state()
  1037.  
  1038.     
  1039.     def destroy(self):
  1040.         '''
  1041.         Declare that you are done with this OptionParser.  This cleans up
  1042.         reference cycles so the OptionParser (and all objects referenced by
  1043.         it) can be garbage-collected promptly.  After calling destroy(), the
  1044.         OptionParser is unusable.
  1045.         '''
  1046.         OptionContainer.destroy(self)
  1047.         for group in self.option_groups:
  1048.             group.destroy()
  1049.         
  1050.         del self.option_list
  1051.         del self.option_groups
  1052.         del self.formatter
  1053.  
  1054.     
  1055.     def _create_option_list(self):
  1056.         self.option_list = []
  1057.         self.option_groups = []
  1058.         self._create_option_mappings()
  1059.  
  1060.     
  1061.     def _add_help_option(self):
  1062.         self.add_option('-h', '--help', action = 'help', help = _('show this help message and exit'))
  1063.  
  1064.     
  1065.     def _add_version_option(self):
  1066.         self.add_option('--version', action = 'version', help = _("show program's version number and exit"))
  1067.  
  1068.     
  1069.     def _populate_option_list(self, option_list, add_help = True):
  1070.         if self.standard_option_list:
  1071.             self.add_options(self.standard_option_list)
  1072.         if option_list:
  1073.             self.add_options(option_list)
  1074.         if self.version:
  1075.             self._add_version_option()
  1076.         if add_help:
  1077.             self._add_help_option()
  1078.  
  1079.     
  1080.     def _init_parsing_state(self):
  1081.         self.rargs = None
  1082.         self.largs = None
  1083.         self.values = None
  1084.  
  1085.     
  1086.     def set_usage(self, usage):
  1087.         if usage is None:
  1088.             self.usage = _('%prog [options]')
  1089.         elif usage is SUPPRESS_USAGE:
  1090.             self.usage = None
  1091.         elif usage.lower().startswith('usage: '):
  1092.             self.usage = usage[7:]
  1093.         else:
  1094.             self.usage = usage
  1095.  
  1096.     
  1097.     def enable_interspersed_args(self):
  1098.         '''Set parsing to not stop on the first non-option, allowing
  1099.         interspersing switches with command arguments. This is the
  1100.         default behavior. See also disable_interspersed_args() and the
  1101.         class documentation description of the attribute
  1102.         allow_interspersed_args.'''
  1103.         self.allow_interspersed_args = True
  1104.  
  1105.     
  1106.     def disable_interspersed_args(self):
  1107.         """Set parsing to stop on the first non-option. Use this if
  1108.         you have a command processor which runs another command that
  1109.         has options of its own and you want to make sure these options
  1110.         don't get confused.
  1111.         """
  1112.         self.allow_interspersed_args = False
  1113.  
  1114.     
  1115.     def set_process_default_values(self, process):
  1116.         self.process_default_values = process
  1117.  
  1118.     
  1119.     def set_default(self, dest, value):
  1120.         self.defaults[dest] = value
  1121.  
  1122.     
  1123.     def set_defaults(self, **kwargs):
  1124.         self.defaults.update(kwargs)
  1125.  
  1126.     
  1127.     def _get_all_options(self):
  1128.         options = self.option_list[:]
  1129.         for group in self.option_groups:
  1130.             options.extend(group.option_list)
  1131.         
  1132.         return options
  1133.  
  1134.     
  1135.     def get_default_values(self):
  1136.         if not self.process_default_values:
  1137.             return Values(self.defaults)
  1138.         defaults = None.defaults.copy()
  1139.         for option in self._get_all_options():
  1140.             default = defaults.get(option.dest)
  1141.             if isbasestring(default):
  1142.                 opt_str = option.get_opt_string()
  1143.                 defaults[option.dest] = option.check_value(opt_str, default)
  1144.                 continue
  1145.         return Values(defaults)
  1146.  
  1147.     
  1148.     def add_option_group(self, *args, **kwargs):
  1149.         if type(args[0]) is types.StringType:
  1150.             group = OptionGroup(self, *args, **kwargs)
  1151.         elif len(args) == 1 and not kwargs:
  1152.             group = args[0]
  1153.             if not isinstance(group, OptionGroup):
  1154.                 raise TypeError, 'not an OptionGroup instance: %r' % group
  1155.             if group.parser is not self:
  1156.                 raise ValueError, 'invalid OptionGroup (wrong parser)'
  1157.         else:
  1158.             raise TypeError, 'invalid arguments'
  1159.         None.option_groups.append(group)
  1160.         return group
  1161.  
  1162.     
  1163.     def get_option_group(self, opt_str):
  1164.         if not self._short_opt.get(opt_str):
  1165.             pass
  1166.         option = self._long_opt.get(opt_str)
  1167.         if option and option.container is not self:
  1168.             return option.container
  1169.  
  1170.     
  1171.     def _get_args(self, args):
  1172.         if args is None:
  1173.             return sys.argv[1:]
  1174.         return None[:]
  1175.  
  1176.     
  1177.     def parse_args(self, args = None, values = None):
  1178.         """
  1179.         parse_args(args : [string] = sys.argv[1:],
  1180.                    values : Values = None)
  1181.         -> (values : Values, args : [string])
  1182.  
  1183.         Parse the command-line options found in 'args' (default:
  1184.         sys.argv[1:]).  Any errors result in a call to 'error()', which
  1185.         by default prints the usage message to stderr and calls
  1186.         sys.exit() with an error message.  On success returns a pair
  1187.         (values, args) where 'values' is an Values instance (with all
  1188.         your option values) and 'args' is the list of arguments left
  1189.         over after parsing options.
  1190.         """
  1191.         rargs = self._get_args(args)
  1192.         if values is None:
  1193.             values = self.get_default_values()
  1194.         self.rargs = rargs
  1195.         self.largs = largs = []
  1196.         self.values = values
  1197.         
  1198.         try:
  1199.             stop = self._process_args(largs, rargs, values)
  1200.         except (BadOptionError, OptionValueError):
  1201.             err = None
  1202.             self.error(str(err))
  1203.  
  1204.         args = largs + rargs
  1205.         return self.check_values(values, args)
  1206.  
  1207.     
  1208.     def check_values(self, values, args):
  1209.         '''
  1210.         check_values(values : Values, args : [string])
  1211.         -> (values : Values, args : [string])
  1212.  
  1213.         Check that the supplied option values and leftover arguments are
  1214.         valid.  Returns the option values and leftover arguments
  1215.         (possibly adjusted, possibly completely new -- whatever you
  1216.         like).  Default implementation just returns the passed-in
  1217.         values; subclasses may override as desired.
  1218.         '''
  1219.         return (values, args)
  1220.  
  1221.     
  1222.     def _process_args(self, largs, rargs, values):
  1223.         """_process_args(largs : [string],
  1224.                          rargs : [string],
  1225.                          values : Values)
  1226.  
  1227.         Process command-line arguments and populate 'values', consuming
  1228.         options and arguments from 'rargs'.  If 'allow_interspersed_args' is
  1229.         false, stop at the first non-option argument.  If true, accumulate any
  1230.         interspersed non-option arguments in 'largs'.
  1231.         """
  1232.         while rargs:
  1233.             arg = rargs[0]
  1234.             if arg == '--':
  1235.                 del rargs[0]
  1236.                 return None
  1237.             if None[0:2] == '--':
  1238.                 self._process_long_opt(rargs, values)
  1239.                 continue
  1240.             if arg[:1] == '-' and len(arg) > 1:
  1241.                 self._process_short_opts(rargs, values)
  1242.                 continue
  1243.             if self.allow_interspersed_args:
  1244.                 largs.append(arg)
  1245.                 del rargs[0]
  1246.                 continue
  1247.             return None
  1248.  
  1249.     
  1250.     def _match_long_opt(self, opt):
  1251.         """_match_long_opt(opt : string) -> string
  1252.  
  1253.         Determine which long option string 'opt' matches, ie. which one
  1254.         it is an unambiguous abbreviation for.  Raises BadOptionError if
  1255.         'opt' doesn't unambiguously match any long option string.
  1256.         """
  1257.         return _match_abbrev(opt, self._long_opt)
  1258.  
  1259.     
  1260.     def _process_long_opt(self, rargs, values):
  1261.         arg = rargs.pop(0)
  1262.         if '=' in arg:
  1263.             (opt, next_arg) = arg.split('=', 1)
  1264.             rargs.insert(0, next_arg)
  1265.             had_explicit_value = True
  1266.         else:
  1267.             opt = arg
  1268.             had_explicit_value = False
  1269.         opt = self._match_long_opt(opt)
  1270.         option = self._long_opt[opt]
  1271.         if option.takes_value():
  1272.             nargs = option.nargs
  1273.             if len(rargs) < nargs:
  1274.                 if nargs == 1:
  1275.                     self.error(_('%s option requires an argument') % opt)
  1276.                 else:
  1277.                     self.error(_('%s option requires %d arguments') % (opt, nargs))
  1278.             elif nargs == 1:
  1279.                 value = rargs.pop(0)
  1280.             else:
  1281.                 value = tuple(rargs[0:nargs])
  1282.                 del rargs[0:nargs]
  1283.         elif had_explicit_value:
  1284.             self.error(_('%s option does not take a value') % opt)
  1285.         else:
  1286.             value = None
  1287.         option.process(opt, value, values, self)
  1288.  
  1289.     
  1290.     def _process_short_opts(self, rargs, values):
  1291.         arg = rargs.pop(0)
  1292.         stop = False
  1293.         i = 1
  1294.         for ch in arg[1:]:
  1295.             opt = '-' + ch
  1296.             option = self._short_opt.get(opt)
  1297.             i += 1
  1298.             if not option:
  1299.                 raise BadOptionError(opt)
  1300.             if option.takes_value():
  1301.                 if i < len(arg):
  1302.                     rargs.insert(0, arg[i:])
  1303.                     stop = True
  1304.                 nargs = option.nargs
  1305.                 if len(rargs) < nargs:
  1306.                     if nargs == 1:
  1307.                         self.error(_('%s option requires an argument') % opt)
  1308.                     else:
  1309.                         self.error(_('%s option requires %d arguments') % (opt, nargs))
  1310.                 elif nargs == 1:
  1311.                     value = rargs.pop(0)
  1312.                 else:
  1313.                     value = tuple(rargs[0:nargs])
  1314.                     del rargs[0:nargs]
  1315.             else:
  1316.                 value = None
  1317.             option.process(opt, value, values, self)
  1318.             if stop:
  1319.                 break
  1320.                 continue
  1321.  
  1322.     
  1323.     def get_prog_name(self):
  1324.         if self.prog is None:
  1325.             return os.path.basename(sys.argv[0])
  1326.         return None.prog
  1327.  
  1328.     
  1329.     def expand_prog_name(self, s):
  1330.         return s.replace('%prog', self.get_prog_name())
  1331.  
  1332.     
  1333.     def get_description(self):
  1334.         return self.expand_prog_name(self.description)
  1335.  
  1336.     
  1337.     def exit(self, status = 0, msg = None):
  1338.         if msg:
  1339.             sys.stderr.write(msg)
  1340.         sys.exit(status)
  1341.  
  1342.     
  1343.     def error(self, msg):
  1344.         """error(msg : string)
  1345.  
  1346.         Print a usage message incorporating 'msg' to stderr and exit.
  1347.         If you override this in a subclass, it should not return -- it
  1348.         should either exit or raise an exception.
  1349.         """
  1350.         self.print_usage(sys.stderr)
  1351.         self.exit(2, '%s: error: %s\n' % (self.get_prog_name(), msg))
  1352.  
  1353.     
  1354.     def get_usage(self):
  1355.         if self.usage:
  1356.             return self.formatter.format_usage(self.expand_prog_name(self.usage))
  1357.         return None
  1358.  
  1359.     
  1360.     def print_usage(self, file = None):
  1361.         '''print_usage(file : file = stdout)
  1362.  
  1363.         Print the usage message for the current program (self.usage) to
  1364.         \'file\' (default stdout).  Any occurrence of the string "%prog" in
  1365.         self.usage is replaced with the name of the current program
  1366.         (basename of sys.argv[0]).  Does nothing if self.usage is empty
  1367.         or not defined.
  1368.         '''
  1369.         if self.usage:
  1370.             print >>file, self.get_usage()
  1371.  
  1372.     
  1373.     def get_version(self):
  1374.         if self.version:
  1375.             return self.expand_prog_name(self.version)
  1376.         return None
  1377.  
  1378.     
  1379.     def print_version(self, file = None):
  1380.         '''print_version(file : file = stdout)
  1381.  
  1382.         Print the version message for this program (self.version) to
  1383.         \'file\' (default stdout).  As with print_usage(), any occurrence
  1384.         of "%prog" in self.version is replaced by the current program\'s
  1385.         name.  Does nothing if self.version is empty or undefined.
  1386.         '''
  1387.         if self.version:
  1388.             print >>file, self.get_version()
  1389.  
  1390.     
  1391.     def format_option_help(self, formatter = None):
  1392.         if formatter is None:
  1393.             formatter = self.formatter
  1394.         formatter.store_option_strings(self)
  1395.         result = []
  1396.         result.append(formatter.format_heading(_('Options')))
  1397.         formatter.indent()
  1398.         if self.option_list:
  1399.             result.append(OptionContainer.format_option_help(self, formatter))
  1400.             result.append('\n')
  1401.         for group in self.option_groups:
  1402.             result.append(group.format_help(formatter))
  1403.             result.append('\n')
  1404.         
  1405.         formatter.dedent()
  1406.         return ''.join(result[:-1])
  1407.  
  1408.     
  1409.     def format_epilog(self, formatter):
  1410.         return formatter.format_epilog(self.epilog)
  1411.  
  1412.     
  1413.     def format_help(self, formatter = None):
  1414.         if formatter is None:
  1415.             formatter = self.formatter
  1416.         result = []
  1417.         if self.usage:
  1418.             result.append(self.get_usage() + '\n')
  1419.         if self.description:
  1420.             result.append(self.format_description(formatter) + '\n')
  1421.         result.append(self.format_option_help(formatter))
  1422.         result.append(self.format_epilog(formatter))
  1423.         return ''.join(result)
  1424.  
  1425.     
  1426.     def _get_encoding(self, file):
  1427.         encoding = getattr(file, 'encoding', None)
  1428.         if not encoding:
  1429.             encoding = sys.getdefaultencoding()
  1430.         return encoding
  1431.  
  1432.     
  1433.     def print_help(self, file = None):
  1434.         """print_help(file : file = stdout)
  1435.  
  1436.         Print an extended help message, listing all options and any
  1437.         help text provided with them, to 'file' (default stdout).
  1438.         """
  1439.         if file is None:
  1440.             file = sys.stdout
  1441.         encoding = self._get_encoding(file)
  1442.         file.write(self.format_help().encode(encoding, 'replace'))
  1443.  
  1444.  
  1445.  
  1446. def _match_abbrev(s, wordmap):
  1447.     """_match_abbrev(s : string, wordmap : {string : Option}) -> string
  1448.  
  1449.     Return the string key in 'wordmap' for which 's' is an unambiguous
  1450.     abbreviation.  If 's' is found to be ambiguous or doesn't match any of
  1451.     'words', raise BadOptionError.
  1452.     """
  1453.     if s in wordmap:
  1454.         return s
  1455.     possibilities = [ word for word in wordmap.keys() if word.startswith(s) ]
  1456.     if len(possibilities) == 1:
  1457.         return possibilities[0]
  1458.     if not None:
  1459.         raise BadOptionError(s)
  1460.     possibilities.sort()
  1461.     raise AmbiguousOptionError(s, possibilities)
  1462.  
  1463. make_option = Option
  1464.